<template>
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <!-- 自定义上传http-request -->
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadImage(e) {
    //   console.log(e)// file
      const file = e.file
      //   1.创建 COS 实例：
      const cos = new COS({
        SecretId: 'AKIDOcbKn0wfDVbU9Ykst75oKeniW6QUHqb8',
        SecretKey: 'LQEoFRRDl6BXnskSvBG6lDSWP8h6KLAo'
      })
      cos.putObject({
        Bucket: 'web90-1318398395',
        Region: 'ap-nanjing',
        Key: 'e.file',
        Body: file,
        ContentType: 'image/jpeg'
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
        //   console.log(data)// Location是图片地址
          // v-model双向绑定 子传父 input事件传给父组件  地址前面要加http://
          this.$emit('input', 'http://' + data.Location)
        } else {
          console.error(err)
        }
      })
    }
  }
}
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
